<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { createCaseApi, updateCaseApi, getCaseDetailApi } from "@/api/case"
import { type CreateOrUpdateCaseRequestData } from "@/api/case/types"
import { type FormInstance, type FormRules, ElMessage, dayjs } from "element-plus"
import { useRouter } from "vue-router"
import IEditor from "@/components/IEditor/index.vue"
import UploadImage from "@/components/UploadImage/index.vue"

defineOptions({
  // 命名当前组件
  name: "CaseOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const loading = ref<boolean>(false)

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateCaseRequestData = {
  id,
  title: "",
  abstract: "",
  tags: "",
  content: "",
  address: "",
  publish_date: dayjs().format("YYYY-MM-DD")
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateCaseRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateCaseRequestData> = {
  title: [{ required: true, trigger: "blur", message: "请输入标题" }],
  abstract: [{ required: true, trigger: "blur", message: "请输入摘要" }],
  tags: [{ required: true, trigger: "blur", message: "请输入标签" }],
  content: [{ required: true, trigger: "blur", message: "请输入内容" }],
  address: [{ required: true, trigger: "blur", message: "请输入地址" }],
  publish_date: [{ required: true, trigger: "blur", message: "请输入发布日期" }],
  cover_url: [{ required: true, trigger: "blur", message: "请上传封面图片" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createCaseApi : updateCaseApi
    formData.value.tags = formData.value.tags?.replace(/，/g, ",")
    formData.value.tags_en = formData.value.tags_en?.replace(/，/g, ",")
    formData.value.publish_date = dayjs(formData.value.publish_date).format("YYYY-MM-DD")
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        router.push("/case")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

const gotoList = () => {
  router.push("/case")
}

//#region 查
const getCaseDetail = () => {
  if (!id) {
    return
  }
  getCaseDetailApi(id)
    .then(async ({ data }) => {
      formData.value = data
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
onMounted(() => {
  getCaseDetail()
})

const dialogImgVisible = ref<boolean>(false)
const file = ref<any>()
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined || "" ? "新增" : "修改案例" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="index" label="顺序索引">
          <el-input-number v-model="formData.index" placeholder="请输入" :min="1" :precision="0" />
        </el-form-item>
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="title_en" label="英文标题">
          <el-input v-model="formData.title_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="publish_date" label="发布时间">
          <el-date-picker v-model="formData.publish_date" placeholder="请选择"
        /></el-form-item>
        <el-form-item prop="cover_url" label="封面">
          <upload-image v-model="formData.cover_url" />
        </el-form-item>
        <el-form-item prop="abstract" label="摘要">
          <el-input v-model="formData.abstract" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="abstract_en" label="英文摘要">
          <el-input v-model="formData.abstract_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="tags" label="标签">
          <el-input v-model="formData.tags" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="tags_en" label="标签英文">
          <el-input v-model="formData.tags_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="content" label="内容">
          <IEditor v-model="formData.content" />
        </el-form-item>
        <el-form-item prop="content_en" label="内容(英文)">
          <IEditor v-model="formData.content_en" />
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="formData.address" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="address_en" label="英文地址">
          <el-input v-model="formData.address_en" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
    <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
      <img :src="file" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
